﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using Taurus.Platform.BLL;
using Taurus.Platform.DTO;
using Taurus.Platform.Net;
using Taurus.Components;
using Component = Taurus.Components.Component;
using Taurus.Platform.UI;
using Taurus.BLL;
using System.Threading;

namespace Taurus
{
    public partial class Taurus : Form
    {

        #region field
        private AccountBll _accountBll = new AccountBll();
        #endregion

        #region delegate

        delegate void ChangeComponentUICallback(Component c);

        #endregion

        #region construction
        public Taurus()
        {
            InitializeComponent();
        }
        #endregion

        #region private
        private void BindComponents()
        {
            List<IComponentFactory> list = ComponentsBll.AllComponents;
            foreach (var cf in list)
            {
                Component c = cf.GetComponent();
                ConstructComponent(c, 组件ToolStripMenuItem);
                
            }
        }

        private void ConstructComponent(Component component, ToolStripMenuItem menu)
        {
            ToolStripMenuItem menuItem = new ToolStripMenuItem();
            menuItem.Tag = component;
            menuItem.Text = string.Format("{0}[{1}]", component.Name, component.Version);
            component.StartInit += new EventHandler(component_StartInit);
            component.EndInit += new EventHandler(component_EndInit);
            component.NewMessage += new EventHandler<MsgEventArgs>(component_NewMessage);
            menuItem.Click+=new EventHandler(componentMenuItem_Click);
            menu.DropDownItems.Add(menuItem);
            if (component.Components != null)
            {
                foreach (var item in component.Components)
                {
                    ConstructComponent(item, menuItem);
                }
            }
        }
       
        private void InitComponent(ToolStripMenuItem item)
        {
            Component com = (Component)item.Tag;
            com.InitComponent();
            Thread.Sleep(500);
            for (int i = 0; i < item.DropDownItems.Count; i++)
            {
                InitComponent((ToolStripMenuItem)item.DropDownItems[i]);
            }
            
        }

        private void ChangeComponentUI(Component c)
        {
            mainPanel.Controls.Clear();
            UserControl uc = c.GetUI();
            mainPanel.Controls.Add(uc);
        }

        private void BindEvent() 
        {
            foreach (var item in accountContextMenu.Items)
            {
                if (item is KryptonContextMenuItems)
                {

                    foreach (var menuItem in ((KryptonContextMenuItems)item).Items)
                    {
                        ((KryptonContextMenuItem)menuItem).Click += new EventHandler(menuItem_Click);
                    }
                }
            }
        }

        private void BindAccount()
        {
            accountListbox.Items.Clear();
            foreach (var account in _accountBll.GetAllAccount().OrderBy(a=>a.IsPublic).ToList())
            {
                KryptonListItem li = new KryptonListItem();
                li.Tag = account;
                li.ShortText = account.Name;
                li.LongText = account.Email;
                li.Image = account.IsPublic? global::Taurus.Properties.Resources.user_orange : global::Taurus.Properties.Resources.user;
                accountListbox.Items.Add(li);
            }
        }

        private void BindSmallAccount()
        {
            if (accountListbox.SelectedItem != null)
            {
                KryptonListItem li = (KryptonListItem)accountListbox.SelectedItem;
                UserAccount myAccount = (UserAccount)li.Tag;
                var t = from i in myAccount.WrapperSmallAccount select new { i.UID, i.Name, i.Email };
                accountDataGridView.DataSource = t.ToList();
            }
        }

        private AccountDialog GetAccountDialog()
        {
            return GetAccountDialog(null);
        }

        private AccountDialog GetAccountDialog(UserAccount account)
        {
            AccountDialog ad = new AccountDialog(account);
            return ad;
        }

        #endregion

        #region event

        void component_EndInit(object sender, EventArgs e)
        {
            lblStatus.Image = null;
            Component component = (Component)sender;
            lblStatus.Text = component.Name + "组件加载完毕";
        }

        void component_StartInit(object sender, EventArgs e)
        {
            lblStatus.Image = global::Taurus.Properties.Resources.loading;
            Component component = (Component)sender;
            lblStatus.Text = component.Name + "组件开始加载";
        }

        void component_NewMessage(object sender, MsgEventArgs e)
        {
            lblStatus.Text = e.Msg;
            if (e.Msg == string.Empty)
            {
                lblStatus.Image = null;
            }
            else
            {
                lblStatus.Image = global::Taurus.Properties.Resources.loading;
            }
        }

        private void Taurus_Load(object sender, EventArgs e)
        {
            BindEvent();
            BindAccount();
            BindComponents();
            backgroundWorker1.RunWorkerAsync();
        }
        void componentMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            if (mi.DropDownItems.Count == 0)
            {
                if (mainPanel.InvokeRequired)
                {
                    mainPanel.Invoke(new ChangeComponentUICallback(ChangeComponentUI), new object[] { mi.Tag });

                }
                else
                {
                    ChangeComponentUI((Component)mi.Tag);
                }
            }
        }

        void menuItem_Click(object sender, EventArgs e)
        {
            KryptonContextMenuItem item = (KryptonContextMenuItem)sender;            
            AccountDialog ad;
            KryptonListItem li;
            switch (item.Tag.ToString())
            {
                case "add":
                    ad = GetAccountDialog();
                    if (ad.ShowDialog() == DialogResult.OK)
                    {
                        if (_accountBll.UpdateAccount(ad.UserAccount,true))
                            BindAccount();
                        else
                            MessageBox.Show("账号密码错误，无法记录");
                    }
                    break;
                case "edit":
                    
                    li = (KryptonListItem)accountListbox.SelectedItem;
                    ad = GetAccountDialog((UserAccount)li.Tag);
                    if (ad.ShowDialog() == DialogResult.OK)
                    {
                        if (_accountBll.UpdateAccount(ad.UserAccount,true))
                            BindAccount();
                        else
                            MessageBox.Show("账号密码错误，无法记录");
                    }
                    break;
                case "delete":
                    if (MessageBox.Show("确定要删除账号吗？","删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    {
                        li = (KryptonListItem)accountListbox.SelectedItem;
                        _accountBll.DeleteAccount((UserAccount)li.Tag);
                        BindAccount();
                    }
                    break;
                case "addSA":
                    ad = GetAccountDialog();
                    if (ad.ShowDialog() == DialogResult.OK)
                    {
                        li = (KryptonListItem)accountListbox.SelectedItem;
                        UserAccount myAccount = (UserAccount)li.Tag;
                        if (_accountBll.UpdateAccount(ad.UserAccount, true))
                        {
                            myAccount.SmallAccount.Add(ad.UserAccount.UID);
                            _accountBll.UpdateAccount(myAccount);
                            BindAccount();
                            BindSmallAccount();
                        }
                        else
                        {
                            MessageBox.Show("小号的用户名或密码错误");
                        }
                    }
                    break;
                default:
                    break;
            }
            
        }

        private void accountContextMenu_Opening(object sender, CancelEventArgs e)
        {
            if (accountListbox.SelectedItem == null)
            {
                kryptonContextMenuItem5.Enabled = false;
                kryptonContextMenuItem3.Enabled = false;
                kryptonContextMenuItem4.Enabled = false;
            }
            else
            {
                kryptonContextMenuItem5.Enabled = true;
                kryptonContextMenuItem3.Enabled = true;
                kryptonContextMenuItem4.Enabled = true;
            }
        }

        private void accountDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (accountDataGridView.Columns[e.ColumnIndex].HeaderText == "删除小号")
            {
                if (MessageBox.Show("确定要删除账号吗？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    string uid = accountDataGridView.CurrentRow.Cells["UID"].Value.ToString();
                    KryptonListItem li = (KryptonListItem)accountListbox.SelectedItem;
                    UserAccount ua = (UserAccount)li.Tag;
                    var t = from i in ua.SmallAccount where i == uid select i;
                    ua.SmallAccount.Remove(t.FirstOrDefault());
                    _accountBll.UpdateAccount(ua);
                }
            }
        }

        private void accountListbox_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindSmallAccount();
            KryptonListItem li = (KryptonListItem)accountListbox.SelectedItem;
            UserAccount myAccount = (UserAccount)li.Tag;
            heardImg.Image = _accountBll.GetAccountHeadImg(myAccount);
        }

        private void 插件设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PlugsUserControl control = new PlugsUserControl();
            control.Dock = DockStyle.Fill;

            mainPanel.Controls.Clear();
            mainPanel.Controls.Add(control);
        }

        private void 账号设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mainPanel.Controls.Clear();
            mainPanel.Controls.Add(pnlAccount);
        }

        private void btnUpdateFriendInfo_Click(object sender, EventArgs e)
        {
            
            if (accountListbox.SelectedItem != null)
            {
                KryptonListItem li = (KryptonListItem)accountListbox.SelectedItem;
                FriendDialog fd = new FriendDialog((UserAccount)li.Tag);
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    MessageBox.Show(fd.SelectFriend.Name);
                }
            }
            else
            {
                MessageBox.Show("未选择账号");
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < accountListbox.Items.Count; i++)
            {
                KryptonListItem li = (KryptonListItem)accountListbox.Items[i];
                UserAccount myAccount = (UserAccount)li.Tag;
                lblStatus.Image = global::Taurus.Properties.Resources.loading;
                lblStatus.Text = string.Format("初始化{0}用户信息", myAccount.Name);
                _accountBll.InitAccount(myAccount);
                lblStatus.Image = null;
                _accountBll.UpdateAccount(myAccount);
            }

           
            
            for (int i = 0; i < 组件ToolStripMenuItem.DropDownItems.Count; i++)
            {
                InitComponent((ToolStripMenuItem)组件ToolStripMenuItem.DropDownItems[i]);
            }
        }

        #endregion        

    }
}
